<?php

declare(strict_types=1);

namespace app\backend\controller\sys;

use app\common\controller\Basic;
use app\common\service\sys\FolderService;

/**
 * 我的文件 控制器
 * @author kaige
 * @update  2023-09-01
 * @copyright ©2022 泉州市盛筑信息科技有限公司 版权所有
 */
class Folder extends Basic
{

  // 初始化
  protected function initialize()
  {
    parent::initialize();
    // 当前控制器服务实例化
    $this->service = new FolderService();
  }

  /**
   * 列表
   */
  public function index()
  {
    if ($this->request->isGet()) {
      $data = input('param.');
      $data['user_id'] = $this->user['id'];
      return json($this->service->_list($data));
    }
    return _jerr(1000);
  }

  /**
   * 添加
   */
  public function add()
  {
    if ($this->request->isPost()) {
      $data = input('param.');
      $data['user_id'] = $this->user['id'];
      $this->_form_filter($data);
      return json($this->service->saveForm($data));
    }
    if ($this->request->isGet()) {
      $data = [];
      return _jok('ok', $data);
    }
    return _jerr(1000);
  }

  /**
   * 编辑
   */
  public function edit()
  {
    $id = input('id/d', 0);
    if ($id === 0) {
      return _jerr(1022);
    }
    if ($this->request->isPost()) {
      $data = input('param.');
      $this->_form_filter($data);
      if ($data['user_id'] != $this->user['id']) {
        return _jerr('您非此文件归属人');
      }
      return json($this->service->saveForm($data));
    }
    if ($this->request->isGet()) {
      $data = input('param.');
      $res =  $this->service->_list($data);
      if ($res) {
        if ($res['count'] > 0) {
          $info = $res['data'][0];
          return _jok('ok', $info);
        }
      }
    }
    return _jerr(1000);
  }

  /**
   * 查看
   */
  public function look()
  {
    if ($this->request->isGet()) {
      $data = input('param.');
      $data['user_id'] = $this->user['id'];
      $res =  $this->service->_list($data);
      if ($res) {
        if ($res['count'] > 0) {
          $info = $res['data'][0];
          return _jok('ok', $info);
        }
      }
      return _jerr(1004);
    }
    return _jerr(1000);
  }

  /**
   * 添加编辑-表单数据处理
   */
  protected function _form_filter(&$data)
  {
    url_decode($data);
    if (isset($data['look_user_id']) && !empty($data['look_user_id'])) {
      $arr = parse_ugdc($data['look_user_id']);
      $data['look_user_id'] = $arr ? implode(',', $arr) : '';
    }
  }

  /**
   * 删除
   */
  public function del()
  {
    if ($this->request->isPost()) {
      $id = input('id/d', 0);
      if ($this->service->delete($id)) {
        return _jok(1025);
      };
      return _jerr(1026);
    }
    return _jerr(1000);
  }
}
